package com.joplin.iemsdemo.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.joplin.iemsdemo.R
import com.joplin.iemsdemo.manager.IEMSManager
import com.joplin.iemsdemo.service.IEMSService

class MainActivity : AppCompatActivity() {
    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestPermission()
        findViewById<Button>(R.id.tvIEMSStart).setOnClickListener {
            if (requestPermission()) return@setOnClickListener
            IEMSManager.start()
        }
        findViewById<Button>(R.id.tvIMESStop).setOnClickListener {
            IEMSManager.stop()
        }
        findViewById<Button>(R.id.tvService).setOnClickListener {
            if (requestPermission()) return@setOnClickListener
            if (requestDrawOverlays()) return@setOnClickListener
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(Intent(this, IEMSService::class.java))
            } else {
                startService(Intent(this, IEMSService::class.java))
            }
        }
    }

    private fun checkPermission(): Boolean {
        val hasPermission = ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
        return hasPermission
    }

    private fun canDrawOverlays(): Boolean {
        return Settings.canDrawOverlays(this)
    }

    private fun requestPermission(): Boolean {
        if (!checkPermission()) {
            Toast.makeText(this, "需要授予录音权限", Toast.LENGTH_SHORT).show()
            requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0x1)
            return true
        }
        return false
    }

    private fun requestDrawOverlays(): Boolean {
        if (!canDrawOverlays()) {
            Toast.makeText(this, "需要授予悬浮窗权限", Toast.LENGTH_SHORT).show()
            startActivityForResult(
                Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName())
                ), 1
            );
            return true
        }
        return false
    }
}